import 'dart:async';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

class MainWidget extends StatefulWidget {
  const MainWidget();

  @override
  _MainWidget createState() => _MainWidget();
}

class _MainWidget extends State {
  @override
  void initState() {
    startServer();
    super.initState();
  }

  @override
  void dispose() {
    stopServer();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    HttpClient client = new HttpClient();
    return Center(
      child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            TextButton(
                child: Text("成功请求"),
                onPressed: () async {
                  var dio = Dio();
                  var response = await dio.get('https://jsonplaceholder.typicode.com/posts/1');
                  print('statusCode: ${response.statusCode}');
                }),
            TextButton(
                child: Text("connection timed out"),
                onPressed: () async {
                  HttpClient timeoutClient = new HttpClient();
                  timeoutClient.connectionTimeout = Duration(milliseconds: 10);
                  timeoutClient
                      .getUrl(Uri.parse('https://xxx.com/'))
                      .then((HttpClientRequest request) {
                    return request.close();
                  }).then((HttpClientResponse response) {
                    print('statusCode: ${response.statusCode}');
                  });
                }),
            TextButton(
                child: Text("404请求报错"),
                onPressed: () async {
                  client
                      .getUrl(serverUrl.resolve('/404'))
                      .then((HttpClientRequest request) {
                    return request.close();
                  }).then((HttpClientResponse response) {
                    print('statusCode: ${response.statusCode}');
                  });
                }),
            TextButton(
                child: Text("500请求报错"),
                onPressed: () async {
                  client
                      .getUrl(serverUrl.resolve('/500'))
                      .then((HttpClientRequest request) {
                    return request.close();
                  }).then((HttpClientResponse response) {
                    print('statusCode: ${response.statusCode}');
                  });
                }),
          ]),
    );
  }
}


class NetworkPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Network Test'),
      ),
      body: Center(
        child: MainWidget(),
      ),
    );
  }
}

/// The current server instance.
HttpServer? _server;

/// The URL for the current server instance.
Uri get serverUrl => Uri.parse('http://localhost:${_server!.port}');

/// Starts a new HTTP server.
Future<void> startServer() async {
  _server = (await HttpServer.bind('localhost', 0))
    ..listen((request) async {
      var path = request.uri.path;
      var response = request.response;

      if (path == '/404') {
        response
          ..statusCode = 404
          ..contentLength = 0;
        unawaited(response.close());
        return;
      }

      if (path == '/500') {
        response
          ..statusCode = 500
          ..contentLength = 0;
        unawaited(response.close());
        return;
      }
    });
}

/// Stops the current HTTP server.
void stopServer() {
  if (_server != null) {
    _server!.close();
    _server = null;
  }
}